package com.keba.lamp.ai.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.keba.basic.utils.ArgumentAssert;
import com.keba.basic.utils.DateUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.keba.lamp.ai.service.AiApiKeyService;
import com.keba.basic.base.service.impl.SuperServiceImpl;
import com.keba.lamp.ai.manager.AiApiKeyManager;
import com.keba.lamp.ai.entity.AiApiKey;
import com.keba.lamp.ai.vo.save.AiApiKeySaveVO;
import com.keba.lamp.ai.vo.update.AiApiKeyUpdateVO;
import com.keba.lamp.ai.vo.result.AiApiKeyResultVO;
import com.keba.lamp.ai.vo.query.AiApiKeyPageQuery;

/**
 * <p>
 * 业务实现类
 * apikey管理
 * </p>
 *
 * @author twg
 * @date 2025-03-02 19:15:52
 * @create [2025-03-02 19:15:52] [twg] [代码生成器生成]
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class AiApiKeyServiceImpl extends SuperServiceImpl<AiApiKeyManager, Long, AiApiKey> implements AiApiKeyService {


    @Override
    protected <SaveVO> AiApiKey saveBefore(SaveVO saveVO) {
        AiApiKeySaveVO aiApiKeySaveVO = (AiApiKeySaveVO) saveVO;
        aiApiKeySaveVO.setApiKey(IdUtil.fastSimpleUUID()).setName(StrUtil.isBlank(aiApiKeySaveVO.getName()) ? StrUtil.format("api-key-{}", DateUtil.format(DateUtil.date(), DatePattern.PURE_DATETIME_MS_PATTERN) + RandomUtil.randomNumbers(4)) : aiApiKeySaveVO.getName());
        ArgumentAssert.isFalse(superManager.exists(Wrappers.lambdaQuery(AiApiKey.class).eq(AiApiKey::getName, aiApiKeySaveVO.getName()).eq(AiApiKey::getApiKey, aiApiKeySaveVO.getApiKey())), "apiKey已存在");
        return super.saveBefore(aiApiKeySaveVO);
    }

    @Override
    protected <UpdateVO> AiApiKey updateBefore(UpdateVO updateVO) {
        AiApiKeyUpdateVO aiApiKeyUpdateVO = (AiApiKeyUpdateVO) updateVO;
        AiApiKey aiApiKey = getById(aiApiKeyUpdateVO.getId());
        aiApiKeyUpdateVO.setApiKey(aiApiKey.getApiKey());
        ArgumentAssert.isFalse(superManager.exists(Wrappers.lambdaQuery(AiApiKey.class).ne(AiApiKey::getId, aiApiKeyUpdateVO.getId()).eq(AiApiKey::getName, aiApiKeyUpdateVO.getName()).eq(AiApiKey::getApiKey, aiApiKeyUpdateVO.getApiKey())), "apiKey已存在");
        return super.updateBefore(aiApiKeyUpdateVO);
    }
}


